package com.zhugang.week02;

/**
 * @program algorithms
 * @description: getKthFromEnd
 * @author: chanzhugang
 * @create: 2022/05/31 10:21
 */
public class GetKthFromEnd {

    /**
     * 剑指offer22. 链表中倒数第k个节点
     *
     * @param head
     * @param k
     * @return
     */
    public ListNode getKthFromEnd(ListNode head, int k) {
        // 快指针每次后移一位，k--， 判断k == 0 （head = head.next）
        ListNode fast = head;
        while (fast != null) {
            fast = fast.next;
            if (k == 0) {
                head = head.next;
            } else {
                k--;
            }
        }
        return head;
    }

    public ListNode getKthFromEnd2(ListNode head, int k) {
        // fast指针遍历到第k个，slow指针从head开始遍历
        ListNode fast = head;
        int count = 0;
        while (fast != null) {
            count++;
            if (count == k) {
                break;
            }
            fast = fast.next;
        }
        ListNode slow = head;
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }

    public ListNode getKthFromEnd3(ListNode head, int k) {
        // 快慢指针同时往后挪时，相差节点数为k-1，即fast遍历结束，slow为倒数第k个节点
        ListNode slow = head, fast = head;
        int t = 0;
        while (fast != null) {
            if (t >= k) {
                slow = slow.next;
            }
            fast = fast.next;
            t++;
        }
        return slow;
    }

    public class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }
}